package listmapdemo;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

public class shoppingcart {
    Map<product, Integer> cart = new HashMap<>();

    // 添加商品（增加数量）
    public void addProduct(product product) {
        cart.put(product, cart.getOrDefault(product, 0) + 1);
    }

    // 移除商品
    public void removeProduct(product product) {
        cart.remove(product);
    }

    // 修改数量
    public void updateQuantity(product product, int quantity) {
        if (quantity <= 0) {
            cart.remove(product);
        } else {
            cart.put(product, quantity);
        }
    }

    // 计算总价
    public double calculateTotalPrice() {
        return cart.entrySet().stream()
                .mapToDouble(entry -> entry.getKey().price * entry.getValue())
                .sum();
    }

    // 按分类统计商品
    public Map<Double, Double>统计ByCategory() {
        return cart.entrySet().stream()
                .collect(java.util.stream.Collectors.groupingBy(
                        entry -> entry.getKey().category,
                        java.util.stream.Collectors.summingDouble(entry -> entry.getKey().price * entry.getValue())
                ));
    }
    // 使用迭代器安全删除元素
    public void removeIf(java.util.function.Predicate<product> predicate) {
        cart.keySet().removeIf(predicate);
    }

    // 使用Lambda表达式遍历购物车
    public void forEachProduct(Consumer<Map.Entry<product, Integer>> action) {
        cart.forEach((product, quantity) -> action.accept(Map.entry(product, quantity)));
    }
}


